using System;
using System.Diagnostics;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading;
using Infrastructure;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace HostRole
{
    public class WorkerRole : RoleEntryPoint
    {
        private ServiceHost _host;

        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.WriteLine("HostRole entry point called", "Information");

            while (true)
            {
                Thread.Sleep(10000);
                Trace.WriteLine("Working", "Information");
            }
        }

        public override Boolean OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            CloudStorageAccount.SetConfigurationSettingPublisher((name, setter) => setter(RoleEnvironment.GetConfigurationSettingValue(name)));

            var diagnostics = new AzureDiagnostics.TableStorageTraceListener();
            diagnostics.Name = "dotnetmarche";

            Trace.Listeners.Add(diagnostics);
            Trace.AutoFlush = true;

            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
            StartHost();
            return base.OnStart();
        }

        public override void OnStop()
        {
            _host.Close();
            base.OnStop();
        }

        private void StartHost()
        {
            Trace.TraceInformation("Starting WCF service host...");
            


            try
            {
                var ipEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["External"].IPEndpoint;

                Trace.TraceInformation("Uri {0}", ipEndPoint);
                var uri = new Uri(String.Format("http://{0}/commands", ipEndPoint));
                _host = new InformationServiceHost(typeof(InformationService), uri);

                //var binding = new BasicHttpBinding
                //    {
                //        HostNameComparisonMode = HostNameComparisonMode.Exact
                //    };
                //_host.AddServiceEndpoint(typeof(IInformationService), binding, String.Format("http://{0}/External", RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["External"].IPEndpoint));
                
                //_host.AddServiceEndpoint(typeof(IInformationService), binding, address);

                

                _host.Open();
                Trace.TraceInformation("WCF service host started successfully.");
            }
            catch (TimeoutException timeoutException)
            {
                Trace.TraceError("The service operation timed out. {0}", timeoutException.Message);
            }
            catch (CommunicationException communicationException)
            {
                Trace.TraceError("Could not start WCF service host. {0}", communicationException.Message);
            }
            catch (Exception exception)
            {
                Trace.TraceError("Could not start WCF service host. {0}", exception.Message);
            }
        }
    }

    public class InformationServiceHost : ServiceHost
    {
        public InformationServiceHost(Type serviceType, params Uri[] baseAddresses) 
            : base(serviceType, baseAddresses)
        {
            this.Description.Behaviors.Add(new ServiceMetadataBehavior
            {
                HttpGetEnabled = true,
                MetadataExporter =
                {
                    PolicyVersion = PolicyVersion.Policy15
                }
            });
        }
    }
}
